package me.keiwu.admin.service.impl;

import me.keiwu.admin.dao.GalleryDao;
import me.keiwu.admin.domain.Gallery;
import me.keiwu.admin.service.GalleryService;
import me.keiwu.admin.util.ExceptionUtil;
import me.keiwu.pub.data.cos.UploadResponse;
import me.keiwu.pub.util.DateUtil;
import me.keiwu.pub.util.cos.CosUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by kei on 07/12/2017.
 */
@Service
@Transactional
public class GalleryServiceImpl implements GalleryService {

    private static final Logger logger = LoggerFactory.getLogger(GalleryServiceImpl.class);


    @Value("${cos.bucket.gallery}")
    private String bucket;
    @Value("${gallery.file.allowPrefix}")
    private String allowPrefix;

    private static final List<String> allowPrefixList = new ArrayList<>();


    @Autowired
    private CosUtil cosUtil;
    @Autowired
    private GalleryDao galleryDao;
    @Autowired
    private ExceptionUtil exceptionUtil;


    @PostConstruct
    private void init() {
        String[] prefixs = this.allowPrefix.split(",");
        for (String prefix : prefixs) {
            if (StringUtils.isBlank(prefix)) continue;
            allowPrefixList.add(prefix);
        }
    }



    @Override
    public Page<Gallery> list(int page, int size) {
        Sort sort = new Sort(Sort.Direction.DESC, "createdTime");
        Pageable pageable = new PageRequest(page, size, sort);
        return galleryDao.findAll(pageable);
    }


    @Override
    public Gallery upload(MultipartFile uploadFile, String desc) {
        logger.info("upload file contentType={}", uploadFile.getContentType());
        String prefix = this.getFilePrefix(uploadFile.getContentType());
        prefix = prefix == null ? "png" : prefix;
        if (!allowPrefixList.contains(prefix)) {
            logger.info("not allowed upload such type: {}", uploadFile.getContentType());
            return null;
        }
        String cosPath = MessageFormat.format(
                "/gallery/{0}-{1}.{2}",
                DateUtil.formatDate(new Date(), "yyyyMMddHHmmss", Locale.ENGLISH),
                RandomStringUtils.randomAlphanumeric(6),
                prefix
        );
        try {
            String contentType = uploadFile.getContentType();
            System.err.println(contentType);
            byte[] contentBytes = uploadFile.getBytes();
            UploadResponse resp = cosUtil.upload(this.bucket, cosPath, contentBytes);
            if (resp != null) {
                Gallery gallery = new Gallery();
                gallery.setImgUrl(resp.getSourceUrl());
                gallery.setCosPath(cosPath);
                gallery.setCreatedTime(DateUtil.getUnixTime());
                gallery.setDescription(desc);
                galleryDao.save(gallery);
                return gallery;
            }
        } catch (IOException e) {
            logger.error("get file bytes excetion: ", e);
            exceptionUtil.logError(this.getClass(), "upload", e.getMessage());
        }
        return null;
    }


    @Override
    public void delete(long id) {
        Gallery gallery = galleryDao.findOne(id);
        if (gallery == null) return;
        galleryDao.delete(id);
        cosUtil.delete(bucket, gallery.getCosPath());
    }


    private String getFilePrefix(String fileContentType) {
        String[] str = fileContentType.split("/");
        if (str.length == 2) return str[1];
        return null;
    }



}
